package cn.com.seeederland.gkrpc.transport;

import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * @ClassName HTTPTransportServer
 * @Author SighFate
 * @Date 2020/10/06 23:17
 * @Version 1.0
 * @Description HTTP请求服务端的实现
 */
public class HTTPTransportServer implements TransportServer {

    private static Logger LOGGER = LoggerFactory.getLogger(HTTPTransportServer.class);

    private RequestHandler handler;
    private Server server;

    @Override
    public void init(int port, RequestHandler requestHandler) {
        LOGGER.info("初始化服务端...");
        // 保存请求的数据
        this.handler = requestHandler;
        this.server = new Server(port);

        // 使用Servlet接收请求
        // 创建请求的具体处理
        ServletContextHandler servletContextHandler = new ServletContextHandler();
        // 设置服务端如何处理请求
        server.setHandler(servletContextHandler);

        // 处理所有路径的请求
        ServletHolder servletHolder = new ServletHolder(new RequestServlet());
        servletContextHandler.addServlet(servletHolder, "/*");
        LOGGER.info("初始化服务端完成.");
    }

    @Override
    public void start() {
        try {
            server.start();
        } catch (Exception e) {
            LOGGER.error("服务端启动失败", e);
        }
        try {
            server.join();
        } catch (InterruptedException e) {
            LOGGER.error("服务端启动失败", e);
        }
    }

    @Override
    public void close() {
        try {
            server.stop();
        } catch (Exception e) {
            LOGGER.error("服务端关闭失败", e);
        }
    }

    class RequestServlet extends HttpServlet {
        @Override
        protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            LOGGER.info("开始接收和处理数据...");

            // 请求的数据流
            InputStream inputStream = req.getInputStream();
            // 返回的数据流
            OutputStream outputStream = resp.getOutputStream();

            if (handler != null) {
                handler.onRequest(inputStream, outputStream);
            }

            LOGGER.info("接收和处理数据完成.");
        }
    }
}
